<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Merchantgoods;
use app\common\model\Merchantuser;
use Exception;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;


use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\response\Json;

/**
 * 店铺管理
 *
 * @icon fa fa-circle-o
 */
class Merchant extends Backend
{

    /**
     * Merchant模型对象
     * @var \app\common\model\Merchant
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Merchant;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("openswitchList", $this->model->getOpenswitchList());
    }
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit)
            ->each(function ($v){
                $v["equity"]="否";
                $goods=Merchantgoods::field('1')->where(["merchant_id"=>$v["id"],"status"=>'1',"type_data"=>'1'])
                    ->where("card_type_id > 0")->find();
                if(!empty($goods)) $v["equity"]="是";
            });
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 查看详情
     * */
    public function see($id = null){
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if(!empty($row["images"])) $row["images"]=explode(",",$row["images"]);
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    /**
     * 审核
     * */
    public function operation($id = null){
        $param=$this->request->param();
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($param["status"]==1){
            $param["remark"]='';
            if(empty($row["promotion_code"])){
                $mycardModel = new \app\common\model\Merchant();
                $mycardModel->getPromotionCode($id);//生成二维码
            }
        }
        $result = $row->allowField(true)->save($param);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    /**
     * 验证
     * */
    protected function check($params,$ids=0){
        $data=[
            ['name', 'require', '店铺名称不能为空'],
            ['logo', 'require', '店铺logo不能为空'],
            ['address', 'require', '店铺地址不能为空'],
            ['door_image', 'require', '门头照片不能为空'],
            ['images', 'require', '店内或场地营业照片不能为空'],
            ['license_image', 'require', '营业执照不能为空'],
            ['door_contacts', 'require', '店铺联系人不能为空'],
            ['telephone', 'require', '店铺联系号码不能为空'],
            ['account_number', 'require', '收款账号不能为空'],
            ['account_image', 'require', '收款二维码不能为空'],
        ];
        if(!empty($ids)){
            $ids=Merchantuser::field("id")->where(["mobile"=>$params["mobile"],"merchant_id"=>$ids])->find();
            $data[0]=['mobile', 'require|regex:/^1\d{10}$/|unique:merchantuser,mobile,' .$ids["id"], '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'];
        }else{
            $data[0]=['mobile', 'require|regex:/^1\d{10}$/|unique:merchantuser,mobile' , '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'];
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        return true;
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            $params["status"]='1';
            $params["createtime"]=time();
            $result = $this->model->allowField(true)->insertGetId($params);
            $mycardModel = new \app\common\model\Merchant();
            $mycardModel->getPromotionCode($result);//生成二维码
            $user_data["name"]=$params["name"]."超管账号";
            $user_data["mobile"]=$params["mobile"];
            $user_data["username"]=$params["mobile"];
            $user_data['salt'] = Random::alnum();
            $user_data['password'] = md5(md5("12345678") . $user_data['salt']);
            $user_data["createtime"]=time();
            $user_data["is_super"]='1';
            $user_data["merchant_id"]=$result;//店铺id
            Merchantuser::create($user_data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params,$ids);
        if(!$res) return $res;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 导入
     * */
    public function import(){
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        $user_data=[];
        try {
            foreach ($insert as $k=>$val) {
                if(!empty($val["mobile"])){
                    $user=Merchantuser::field("1")->where(["mobile"=>$val["mobile"]])->find();
                    if($user){
                        unset($insert[$k]);
                    }
                }else{
                    unset($insert[$k]);
                }
                $merchant=$this->model->saveAll($insert);
                if(!empty($merchant)){
                    foreach ($merchant as $k=>$v){
                        $user_data[$k]["name"]=$v["name"]."超管账号";
                        $user_data[$k]["mobile"]=$v["mobile"];
                        $user_data[$k]["username"]=$v["mobile"];
                        $user_data[$k]['salt'] = Random::alnum();
                        $user_data[$k]['password'] = md5(md5("12345678") . $user_data[$k]['salt']);
                        $user_data[$k]["createtime"]=time();
                        $user_data[$k]["is_super"]='1';
                        $user_data[$k]["merchant_id"]=$v["id"];//店铺id
                    }
                    if(!empty($user_data)){
                        Merchantuser::insertAll($user_data);
                    }
                }
            }
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
